const express = require('express')
const http = require('http')
const { Server } = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: '*', // 允许所有来源
    methods: ['GET', 'POST'],
  },
})
const fs = require('fs')

io.on('connection', (socket) => {
  // console.log('A user connected')
  socket.on('chat', (message) => {
    console.log('Received message:', message)

    // 假设这里进行一些处理，然后将消息回传给客户端
    // 为简化示例，我们直接将接收到的消息回传
    console.log('hhh')
    socket.emit('chat_output', `Echo: ${message}`)
  })

  socket.on('attack', (mode, choice) => {
    console.log(mode, choice)
    // 模拟发送日志输出
    let counter = 0
    const attackInterval = setInterval(() => {
      // const log = []
      socket.emit('output', { output: `Attack log message ${++counter}` })
      // // console.log(`Attack log message ${++counter}`)
      // socket.emit('attack_output', { output: log[counter++] })
      if (counter >= 3) clearInterval(attackInterval) // 停止发送消息
    }, 1000)
    // 模拟攻击过程和结果
    setTimeout(() => {
      // console.log(data)
      let result
      // console.log('attack_type:' + data.params.attack_type)
      if (mode === 1) {
        result = {
          metrics: {
            0: {
              precision: 0.62,
              recall: 0.74,
              'f1-score': 0.68,
              support: 10000,
            },
            1: {
              precision: 0.68,
              recall: 0.55,
              'f1-score': 0.61,
              support: 10000,
            },
          },
        }
      } else if (mode === 0) {
        result = {
          pic: [
            '@/assets/attack_images/result1.png',
            '@/assets/attack_images/result2.png',
            '@/assets/attack_images/result3.png',
            '@/assets/attack_images/result4.png',
            '@/assets/attack_images/result5.png',
            '@/assets/attack_images/result6.png',
            '@/assets/attack_images/result7.png',
            '@/assets/attack_images/result8.png',
            '@/assets/attack_images/result9.png',
            '@/assets/attack_images/result10.png',
          ],
        }
      } else if (mode === 2) {
        result = {
          pic: ['@/assets/attack_images/result11.png'],
        }
      }
      // console.log(result)
      socket.emit('attack_result', result)
    }, 3000) // 假设训练需要3秒钟
  })

  socket.on('train', (data) => {
    console.log(data)
    // 模拟发送日志输出
    let counter = 0
    const trainInterval = setInterval(() => {
      socket.emit('output', { output: `Train log message ${++counter}` })
      if (counter >= 3) clearInterval(trainInterval) // 停止发送消息
    }, 1000) // 让日志输出间隔适当长些，每秒一次

    // 模拟训练过程和结果
    setTimeout(() => {
      // 定义随机长度，例如，从5到20之间
      const length = Math.floor(Math.random() * (30 - 5 + 1) + 5)

      // 初始化准确率和损失值数组
      const acc = []
      const loss = []

      // 填充数组，让acc逐渐增加，loss逐渐减少
      let baseAcc = 0.5 // 初始准确率
      let baseLoss = 0.5 // 初始损失

      for (let i = 0; i < length; i++) {
        baseAcc += (1 - baseAcc) * Math.random() * 0.1 // 随机增长，逐渐接近1
        baseLoss *= 1 - Math.random() * 0.1 // 随机减少，逐渐接近0
        acc.push(baseAcc.toFixed(2))
        loss.push(baseLoss.toFixed(2))
      }

      // 假装这是训练过程产生的结果
      const mockResult = {
        acc, // 准确率数组
        loss, // 损失值数组
      }

      // 向客户端发送train_result事件和模拟的结果数据
      socket.emit('train_result', mockResult)
      console.log(mockResult)
    }, 3000) // 假设训练需要3秒钟
  })

  socket.on('disconnect', () => {
    // console.log('User disconnected')
  })

  socket.on('model_use', (data) => {
    if (data.choice === 6) {
      setTimeout(() => {
        // 图片文件的路径
        console.log('6')
        // const imagePath = 'D:\\Project\\隐私镖客-vuestic\\计设\\public\\logo.png'

        // // 同步读取文件并转换为Base64
        // const imageAsBase64 = fs.readFileSync(imagePath, 'base64')

        // 发送Base64编码的图片
        const classes = ['cat', 'dog', 'hh']
        const category_counts = [2, 3, 5]
        socket.emit('eval_result', {
          path: '../../../public/figures/showFigure/show_images.png',
          classes: classes,
          category_counts: category_counts,
          accuracy: 0.5,
          loss: 0.6,
        })
      }, 3000) // 假设处理需要3秒钟
    } else {
      setTimeout(() => {
        console.log('7')
        // const imagePath = 'D:\\Project\\隐私镖客-vuestic\\计设\\public\\logo.png'
        // const imageAsBase64 = fs.readFileSync(imagePath, 'base64')
        socket.emit('eval_result', {
          path: '../../../public/figures/showFigure/showOneImage.png',
        })
      }, 3000) // 假设处理需要3秒钟
    }
  })
})

const PORT = 5000 // 可以根据需要更改端口
server.listen(PORT, () => {
  // console.log(`Server running on http://localhost:${PORT}`)
})
